<template>
  <div class="container">
    <div class="app-container">
      <el-button type="primary" class="add" @click="addCategory"
        >新增</el-button
      >
      <el-button type="danger" class="deletes" @click="deleteCategories"
        >批量删除</el-button
      >
      <el-table
        v-loading="loading"
        :data="tableData"
        lazy
        stripe
        style="width: 100%"
        class="table"
      >
        <el-table-column type="selection" width="80" align="center" />
        <el-table-column type="index" width="200" label="序号" align="center">
        </el-table-column>
        <el-table-column
          prop="name"
          label="类名"
          width="300"
          sortable
          align="center"
        />
        <el-table-column
          prop="productCount"
          label="数量"
          width="280"
          align="center"
        ></el-table-column>
        <el-table-column label="更新时间" align="center">
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            <span style="margin-left: 10px">{{
              leaveTime(scope.row.updateTime)
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="230" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        class="pagination"
        hide-on-single-page
        layout="total, prev, pager, next"
        :total="total"
        :current-page="queryParams.page"
        :page-size="queryParams.pageSize"
        @current-change="currentChange"
      ></el-pagination>
    </div>
    <el-dialog
      width="500px"
      :title="diaLogTitle"
      @close="cancel"
      :visible.sync="showDialog"
    >
      <el-form
        ref="categoryForm"
        label-width="100px"
        :model="categoryForm"
        :rules="rules"
      >
        <el-form-item prop="name" label="农产品类名">
          <el-input
            clearable
            placeholder="请输入农产品的类名"
            style="width: 350px"
            v-model="categoryForm.name"
          />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="16">
              <el-button type="primary" @click="submitForm('categoryForm')"
                >确定</el-button
              >
              <el-button @click="cancel">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCategories,
  addCategory,
  updateCategory,
  deleteCategory,
} from "@/api/category";
import { selectCategory } from "@/api/category";
import moment from "moment";
export default {
  name: "Category",
  data() {
    return {
      loading: true,
      tableData: [],
      categoryForm: {
        name: "",
      },
      rules: {
        name: [
          {
            required: true,
            message: "农产品类名不能为空",
            trigger: "blur",
          },
        ],
      },
      queryParams: {
        page: 1,
        pageSize: 10,
      },
      total: 0,
      showDialog: false,
      diaLogTitle: "",
      message: "",
      type: "",
    };
  },
  created() {
    this.getCategoriesMsg();
  },
  methods: {
    // 获取分类数据
    async getCategoriesMsg() {
      const { total, rows } = await getCategories(this.queryParams);
      this.loading = false;
      this.tableData = rows;
      this.total = total;
    },
    // 编辑分类
    async handleEdit(index, row) {
      // console.log(index, row.id);
      this.showDialog = true;
      this.diaLogTitle = "编辑农产品分类";
      this.categoryForm = await selectCategory(row.id);
      this.message = "修改类名成功";
      this.type = "update";
    },
    // 监听当前页的值
    currentChange(newpage) {
      this.queryParams.page = newpage;
      this.getCategoriesMsg();
    },
    // 添加分类
    addCategory() {
      this.showDialog = true;
      this.diaLogTitle = "新增农产品分类";
      this.message = "新增类名成功";
      this.type = "add";
    },
    // 提交表单
    submitForm() {
      this.$refs.categoryForm.validate(async (valid) => {
        if (valid) {
          if (this.type === "add") {
            await addCategory(this.categoryForm);
          } else if (this.type === "update") {
            await updateCategory(this.categoryForm);
          }
          this.$message({
            type: "success",
            message: this.message,
          });
          this.getCategoriesMsg();
          this.cancel();
        }
      });
    },
    // 取消
    cancel() {
      this.$refs.categoryForm.resetFields(); // 重置表单数据
      this.showDialog = false;
    },
    // 删除农产品分类
    async handleDelete(index, row) {
      this.$confirm("是否删除该分类", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await deleteCategory(row.id).then((res) => {
            this.$message.success("删除类别成功");
            this.queryParams.page = 1;
            this.queryParams.pageSize = 10;
            this.getCategoriesMsg();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 转换日期格式
    leaveTime(value) {
      return moment(value).format("YYYY-MM-DD HH:mm");
    },
    // 批量删除
    deleteCategories() {
      this.$message.success("批量删除");
    },
  },
};
</script>

<style scoped>
.pagination {
  margin-top: 10px;
  text-align: right;
}
</style>
